/**
 * @program: LeetCode
 * @description: LeetCode : 1049. 最后一块石头的重量 II
 * @author: WXY
 * @create: 2023-01-26 14:24
 * @Version 1.0
 **/
/*   01背包问题，  尽可能的分成两堆大小差不多的两份，aim = sum / 2;
 *   重量stones[i]
 *   价值stones[i]
 *   dp[j] = Math.max(dp[j], dp[j - weight[i]] + value[i]);
 *   dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i]);
 **/
public class Num1049_lastStoneWeightII {
    public static int lastStoneWeightII(int[] stones) {
        int sum = 0;
        for (int num : stones) {
            sum += num;
        }
        int aim = sum / 2;
        int[] dp = new int[aim + 1];
        for (int i = 0; i < stones.length; i++) {
            for (int j = aim; j >= 0 && j >= stones[i]; j--) {
                dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i]);
            }
        }
        //dp[aim] 是背包容量为aim的背包最大所背的重量，
        //stongs一共的石头，
        //一堆分为dp[aim]  另外一堆是sum - dp[aim]
        //那么两堆相撞就是  sum - dp[aim] - dp[aim]
        return sum - 2 * dp[aim];
    }

}
